/**
 * HttpDataSource.java
 * @author: liuex
 * 2007-12-30 ����02:44:02
 *
 * note: 
 */
package lex.mtd.core.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.lex.net.log.Log;


public class SunHttpDataSource implements DataSource
{
	private URL url = null;
	private Log log = null;
	private URLConnection con = null;
	private boolean hasPrepared = false;
	// =================================
	private long seek = 0;
	private long contentLength = -1L;
	private InputStream in = null;

	public SunHttpDataSource( URL url, Log log )
	{
		this.url = url;
		this.log = log;
		this.hasPrepared = false;
	}

	@Override
	public long getContentLength( long seek )
	{
		this.seek = seek;
		if( false == this.hasPrepared )
			this.getReady();
		return this.contentLength;
	}

	private boolean getReady()
	{
		if( null == con || false == this.hasPrepared )
		{
			try
			{
				con = url.openConnection();
				HttpUtils.setRequests( con );
				HttpUtils.setSeek( con, seek );
				HttpUtils.log( log, url, Log.Type.SEND, con.getRequestProperties() );
				HttpUtils.log( log, url, Log.Type.REPLY, con.getHeaderFields() );
				this.in = con.getInputStream();
				try
				{
					this.contentLength = Long.parseLong( con.getHeaderField( "Content-Length" ) );
				}
				catch( Exception e )
				{
					log.error( url, e.getLocalizedMessage() );
				}
				this.hasPrepared = true;
			}
			catch( IOException e )
			{
				log.error( url.toString(), e.getLocalizedMessage() );
				this.hasPrepared = false;
			}
		}
		return hasPrepared;
	}

	@Override
	public void close()
	{}

	@Override
	public InputStream openInputStream() throws IOException
	{
		if( false == this.hasPrepared )
			this.getReady();
		return in;
	}

	@Override
	public String getURL()
	{
		return url.toString();
	}
}
